package com.insight.config.shiro.utils;

import cn.hutool.json.JSONObject;
import cn.hutool.jwt.JWT;
import com.insight.common.constant.CommonConstant;
import com.insight.config.mybatis.TenantContext;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Shiro工具类，提供请求信息获取、跨域处理、JWT解析等实用方法。
 */
public class ShiroUtils {

    /**
     * 获取请求的完整URI信息（包含GET参数或POST体）
     * @param request Servlet请求对象
     * @return 请求URI字符串
     */
    public static String getRequestUri(ServletRequest request) {
        String requestUri = "";
        if (request instanceof HttpServletRequest) {
            String url = ((HttpServletRequest) request).getRequestURL().toString();
            if (((HttpServletRequest) request).getMethod().equalsIgnoreCase("GET")) {
                String queryString = ((HttpServletRequest) request).getQueryString();
                requestUri = String.format("requestUri: %s?%s", url, queryString);
            } else {
                String body;
                try {
                    body = request.getInputStream().toString();
                } catch (IOException e) {
                    body = "";
                }
                requestUri = String.format("requestUri: %s body: %s", url, body);
            }
        }
        return requestUri;
    }

    /**
     * 处理跨域请求及多租户上下文设置
     * @param request Servlet请求对象
     * @param response Servlet响应对象
     * @param allowOrigin 是否允许跨域
     * @throws Exception 处理异常
     */
    public static void extracted(ServletRequest request, ServletResponse response, boolean allowOrigin) {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        if (allowOrigin) {
            httpServletResponse.setHeader("Access-control-Allow-Origin", httpServletRequest.getHeader("Origin"));
            httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE");
            httpServletResponse.setHeader("Access-Control-Allow-Headers", httpServletRequest.getHeader("Access-Control-Request-Headers"));
            //update-begin-author:scott date:20200907 for:issues/I1TAAP 前后端分离，shiro过滤器配置引起的跨域问题
            // 是否允许发送Cookie，默认Cookie不包括在CORS请求之中。设为true时，表示服务器允许Cookie包含在请求中。
            httpServletResponse.setHeader("Access-Control-Allow-Credentials", "true");
            //update-end-author:scott date:20200907 for:issues/I1TAAP 前后端分离，shiro过滤器配置引起的跨域问题
        }
        // 跨域时会首先发送一个option请求，这里我们给option请求直接返回正常状态
        if (httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name())) {
            httpServletResponse.setStatus(HttpStatus.OK.value());
            return;
        }
        //update-begin-author:taoyan date:20200708 for:多租户用到
        String tenant_id = httpServletRequest.getHeader(CommonConstant.TENANT_ID);
        TenantContext.setTenant(tenant_id);
    }

    /**
     * 解析JWT并提取Payload部分
     * @param tokenValue JWT字符串
     * @return Payload的JSON对象
     */
    public static JSONObject decodeJwt(String tokenValue) {
        try {
            if (tokenValue == null) {
                throw new IllegalArgumentException("JWT 令牌不能为 null");
            }
            JWT jwt = JWT.of(tokenValue);
            return jwt.getPayloads();
        } catch (Exception e) {
            throw new IllegalArgumentException("解析JWT失败", e);
        }
    }
}
